{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>库存管理系统</title>
    <link href="{% static 'plugins/bootstrap-5.3.0-alpha1-dist/css/bootstrap.min.css' %}" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #4361ee;
            --primary-light: #eef2ff;
            --secondary-color: #3f37c9;
            --accent-color: #4895ef;
            --success-color: #4cc9f0;
            --text-primary: #2b2d42;
            --text-secondary: #6c757d;
            --bg-light: #f8f9fa;
            --border-color: #e9ecef;
        }

        body {
            background-color: #f8fafc;
            font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
            color: var(--text-primary);
        }

        .page-header {
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--border-color);
        }

        .page-header h4 {
            font-weight: 600;
            color: var(--primary-color);
        }

        .search-container {
            background-color: #fff;
            padding: 1.25rem;
            border-radius: 0.75rem;
            box-shadow: 0 2px 12px rgba(0,0,0,0.03);
            margin-bottom: 1.5rem;
            border: 1px solid var(--border-color);
        }

        /* 斑马纹表格样式 */
        .table tbody tr:nth-child(odd) {
            background-color: rgba(67, 97, 238, 0.03);
        }

        .table tbody tr:nth-child(even) {
            background-color: #fff;
        }

        .table tbody tr:hover {
            background-color: rgba(67, 97, 238, 0.08) !important;
            transition: background-color 0.2s ease;
        }

        .form-control {
            border: 1px solid #dee2e6;
            border-radius: 0.5rem;
            padding: 0.5rem 0.75rem;
            transition: all 0.2s ease;
        }

        .form-control:focus {
            border-color: var(--accent-color);
            box-shadow: 0 0 0 0.2rem rgba(67, 97, 238, 0.15);
        }

        .btn {
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-primary:hover {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
            transform: translateY(-1px);
        }

        .btn-light {
            background-color: #fff;
            border: 1px solid #dee2e6;
        }

        .btn-light:hover {
            background-color: #f8f9fa;
            transform: translateY(-1px);
        }

        .shipment-card {
            background-color: #fff;
            border-radius: 0.75rem;
            box-shadow: 0 2px 12px rgba(0,0,0,0.03);
            margin-bottom: 1.25rem;
            transition: all 0.3s ease;
            border: 1px solid var(--border-color);
            overflow: hidden;
        }

        .shipment-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }

        .card-header {
            background: linear-gradient(to right, var(--primary-color), var(--accent-color));
            padding: 0.875rem 1.25rem;
            border-bottom: none;
        }

        .card-header h5 {
            color: white;
            margin: 0;
            font-size: 1rem;
            font-weight: 600;
        }

        .table-container {
            padding: 0.5rem;
        }

        .table {
            margin: 0;
            font-size: 0.9375rem;
            border-collapse: separate;
            border-spacing: 0;
        }

        .table th {
            font-weight: 600;
            color: var(--text-primary);
            background-color: var(--primary-light);
            border-top: none;
            padding: 0.875rem 1rem;
        }

        .table th:first-child {
            border-top-left-radius: 0.5rem;
        }

        .table th:last-child {
            border-top-right-radius: 0.5rem;
        }

        .table td {
            color: var(--text-primary);
            padding: 0.875rem 1rem;
            border-top: 1px solid var(--border-color);
            vertical-align: middle;
        }

        .statistics-bar {
            background-color: var(--primary-light);
            padding: 0.875rem 1.25rem;
            font-size: 0.875rem;
            color: var(--text-secondary);
            border-top: 1px solid var(--border-color);
            border-radius: 0 0 0.75rem 0.75rem;
        }

        .stats-summary {
            background: linear-gradient(to right, var(--primary-light), #f0f7ff);
            border: 1px solid var(--border-color);
            border-radius: 0.75rem;
            padding: 1rem 1.25rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
        }

        .stats-icon {
            background-color: var(--primary-color);
            color: white;
            width: 2.5rem;
            height: 2.5rem;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;
            font-size: 1.25rem;
        }

        .stats-content {
            flex: 1;
        }

        .stats-label {
            font-size: 0.875rem;
            color: var(--text-secondary);
            margin-bottom: 0.25rem;
        }

        .stats-value {
            font-size: 1.125rem;
            font-weight: 600;
            color: var(--text-primary);
        }

        .pagination {
            margin: 1rem 0;
        }

        .page-link {
            padding: 0.5rem 0.75rem;
            color: var(--primary-color);
            background-color: #fff;
            border: 1px solid var(--border-color);
            min-width: 2.25rem;
            text-align: center;
            transition: all 0.2s ease;
        }

        .page-link:hover {
            background-color: var(--primary-light);
            color: var(--primary-color);
        }

        .page-item.active .page-link {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        @media (max-width: 768px) {
            .search-container {
                padding: 1rem;
            }

            .btn-group {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 0.5rem;
            }

            .btn {
                width: 100%;
            }

            .stats-summary {
                flex-direction: column;
                text-align: center;
            }

            .stats-icon {
                margin-right: 0;
                margin-bottom: 0.75rem;
            }
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <div class="row">
            <div class="col-12">
                <div class="page-header">
                    <h4 class="text-center">拣货日志统计</h4>
                </div>

                <!-- 搜索区域 -->
                <div class="search-container">
                    <div class="row g-3">
                        <div class="col-md-2">
                            <label class="form-label small text-muted">库房</label>
                            <input type="text" class="form-control" id="searchHose" placeholder="输入库房"
                                value="{{ request.GET.item_hose }}">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label small text-muted">物品名称</label>
                            <input type="text" class="form-control" id="searchItemName" placeholder="输入物品名称"
                                value="{{ request.GET.item_name }}">
                        </div>
                        <!-- 客户 -->
                        <div class="col-md-2">
                            <label class="form-label small text-muted">客户</label>
                            <input type="text" class="form-control" id="searchitemCustomer" placeholder="请输入客户"
                                   value="{{ request.GET.customer }}">
                        </div>
                        <!-- 操作人 -->
                        <div class="col-md-2">
                            <label class="form-label small text-muted">操作人</label>
                            <input type="text" class="form-control" id="searchOperator" placeholder="请输入操作人"
                                   value="{{ request.GET.operator }}">
                        </div>
                        <!-- 发货类型 -->
                        <div class="col-md-2">
                            <label class="form-label small text-muted">发货类型</label>
                            <select id="searchShipment_type" class="form-select form-control">
                                <option value="">全部类型</option>
                                <option value="有码发货" {% if request.GET.shipment_type == '有码发货' %}selected{% endif %}>有码发货</option>
                                <option value="无码发货" {% if request.GET.shipment_type == '无码发货' %}selected{% endif %}>无码发货</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <div class="btn-group w-100">
                                <button type="button" class="btn btn-primary" id="searchButton">
                                    <i class="bi bi-search me-1"></i> 查询
                                </button>
                                <button type="button" class="btn btn-light" id="resetButton">
                                    <i class="bi bi-arrow-counterclockwise me-1"></i> 重置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 统计信息 -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="stats-summary">
                            <div class="stats-icon">
                                <i class="bi bi-truck"></i>
                            </div>
                            <div class="stats-content">
                                <div class="stats-label">所属库房总数</div>
                                <div class="stats-value" id="totalTrucks">0</div>
                            </div>
                            <div class="stats-divider"></div>
                            <div class="stats-icon">
                                <i class="bi bi-box-seam"></i>
                            </div>
                            <div class="stats-content">
                                <div class="stats-label">总品项数</div>
                                <div class="stats-value" id="totalItems">0</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <nav aria-label="Page navigation" class="d-flex justify-content-end align-items-center h-100">
                            <ul class="pagination mb-0" id="groupPaginationUL"></ul>
                        </nav>
                    </div>
                </div>

                <!-- 数据展示 -->
                <div id="shipmentContainer">
                    {% for group in grouped_data %}
                    <div class="card shipment-card page-item">
                        <div class="card-header">
                            <h5><i class="bi bi-truck me-2"></i>所属库房：{{ group.plate }}</h5>
                        </div>
                        <div class="table-container">
                            <div class="table-responsive">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>客户</th>
                                            <th>物品名称</th>
                                            <th>包装名称</th>
                                            <th>操作人</th>
                                            <th>发货数量</th>
                                            <th>托数</th>
                                            <th>发货类型</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {% for item in group.items %}
                                        <tr>
                                            <td>{{ item.客户 }}</td>
                                            <td>{{ item.物品名称 }}</td>
                                            <td>{{ item.包装名称 }}</td>
                                            <td>{{ item.操作人 }}</td>
                                            <td>{{ item.总数量 }}</td>
                                            <td>{{ item.托数 }}</td>
                                            <td>{{ item.发货类型 }}</td>
                                        </tr>
                                        {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="statistics-bar">
                            <i class="bi bi-clipboard-data me-2"></i>
                            共 <strong>{{ group.paginator.count }}</strong> 条明细
                            <span class="mx-2">|</span>
                            当前页：<strong>{{ group.items|length }}</strong> 条
                            <span class="mx-2">|</span>
                            总发货数量：<strong>{{ group.total_quantity }}</strong>
                            <span class="mx-2">|</span>
                            总托数：<strong>{{ group.total_pallets }}</strong>
                        </div>

                        <!-- 明细行分页导航 -->
                        {% if group.paginator.num_pages > 1 %}
                        <nav aria-label="Items pagination" class="mt-2">
                            <ul class="pagination justify-content-center">
                                {% for p in group.paginator.page_range %}
                                <li class="page-item {% if group.page_obj.number == p %}active{% endif %}">
                                    <a class="page-link"
                                       href="?customer={{ customer }}&item_name={{ item_name }}&operator={{ operator }}&warehouse={{ warehouse }}&shipment_type={{ shipment_type }}&group_page={{ grouped_data.number }}&{{ group.page_key }}={{ p }}">
                                        {{ p }}
                                    </a>
                                </li>
                                {% endfor %}
                            </ul>
                        </nav>
                        {% endif %}
                    </div>
                    {% endfor %}
                </div>

                <!-- 库房分页 -->
                <nav aria-label="Page navigation" class="my-4">
                    <ul class="pagination justify-content-center" id="groupPaginationULBottom"></ul>
                </nav>
            </div>
        </div>
    </div>

    <script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-5.3.0-alpha1-dist/js/bootstrap.bundle.min.js' %}"></script>
    <script>
        $(document).ready(function() {
            const itemsPerPage = 5;
            let currentPage = 1;
            let totalPages = 1;
            let allCards = $('.shipment-card');

            // 初始化统计数据
            window.totalFilteredTrucks = $('.shipment-card').length;
            window.totalFilteredItems = $('.shipment-card tbody tr').length;
            updateStatistics();

            function updateStatistics() {
                $('#totalTrucks').text(window.totalFilteredTrucks || 0);
                $('#totalItems').text(window.totalFilteredItems || 0);
            }

            function initPagination() {
                allCards = $('.shipment-card:visible');
                totalPages = Math.ceil(allCards.length / itemsPerPage);
                updatePagination();
                showPage(currentPage);
            }

            function updatePagination() {
                if (totalPages <= 1) {
                    $('#groupPaginationUL, #groupPaginationULBottom').empty();
                    return;
                }
                const paginationHtml = [];
                paginationHtml.push(`
                    <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                        <a class="page-link" href="#" data-page="prev" aria-label="Previous">
                            <i class="bi bi-chevron-left"></i>
                        </a>
                    </li>
                `);
                for (let i = 1; i <= totalPages; i++) {
                    paginationHtml.push(`
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" data-page="${i}">${i}</a>
                        </li>
                    `);
                }
                paginationHtml.push(`
                    <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                        <a class="page-link" href="#" data-page="next" aria-label="Next">
                            <i class="bi bi-chevron-right"></i>
                        </a>
                    </li>
                `);
                $('#groupPaginationUL, #groupPaginationULBottom').html(paginationHtml.join(''));
            }

            function showPage(page) {
                currentPage = Math.max(1, Math.min(page, totalPages));
                const startIndex = (currentPage - 1) * itemsPerPage;
                const endIndex = startIndex + itemsPerPage;
                allCards.hide();
                allCards.slice(startIndex, endIndex).show();
                updatePagination();
            }

            // 只拦截指定容器内的分页链接（不干扰明细行分页）
            $(document).on('click', '#groupPaginationUL .page-link, #groupPaginationULBottom .page-link', function(e) {
                e.preventDefault();
                const action = $(this).data('page');
                if (action === 'prev') showPage(currentPage - 1);
                else if (action === 'next') showPage(currentPage + 1);
                else if (typeof action === 'number') showPage(action);
            });

            function performSearch() {
                const Sku_name = $('#searchItemName').val().trim().toLowerCase(); // 物品名称
                const operator = $('#searchOperator').val().trim().toLowerCase(); // 操作人
                const SkU_Hose = $('#searchHose').val().trim().toLowerCase(); // 库房
                const shipmentType = $('#searchShipment_type').val().trim();
                const customer = $('#searchitemCustomer').val().trim(); // 客户

                let totalTrucks = 0;
                let totalItems = 0;

                $('.shipment-card').each(function () {
                    const $card = $(this);
                    const $rows = $card.find('tbody tr');
                    let rowMatches = 0;
                    const itemHose = $card.find('.card-header').text().toLowerCase().replace('所属库房：', '').trim();

                    $rows.each(function () {
                        const $row = $(this);
                        const itemCustomer = $row.find('td:eq(0)').text().toLowerCase(); // 客户
                        const itemName = $row.find('td:eq(1)').text().toLowerCase(); // 物品名称列
                        const itemOperator = $row.find('td:eq(3)').text().toLowerCase(); // 操作人
                        const itemShipmentType = $row.find('td:eq(6)').text().trim(); // 发货类型列

                        const match = (!customer || itemCustomer.includes(customer)) &&
                            (!Sku_name || itemName.includes(Sku_name)) &&
                            (!operator || itemOperator.includes(operator)) &&
                            (!SkU_Hose || itemHose.includes(SkU_Hose)) &&
                            (!shipmentType || itemShipmentType === shipmentType);

                        $row.toggle(match);
                        if (match) rowMatches++;
                    });

                    const hasMatch = rowMatches > 0;
                    $card.toggle(hasMatch);

                    if (hasMatch) {
                        totalTrucks++;
                        totalItems += rowMatches;
                    }
                });

                window.totalFilteredTrucks = totalTrucks;
                window.totalFilteredItems = totalItems;
                updateStatistics();
                initPagination();
            }

            $('#searchButton').click(function () {
                const customer = $('#searchitemCustomer').val().trim();
                const itemName = $('#searchItemName').val().trim();
                const operator = $('#searchOperator').val().trim();
                const warehouse = $('#searchHose').val().trim();
                const shipmentType = $('#searchShipment_type').val().trim();
                // 构建查询字符串
                const queryParams = new URLSearchParams({
                    customer: customer,
                    item_name: itemName,
                    operator: operator,
                    warehouse: warehouse,
                    shipment_type: shipmentType
    });
                // 跳转到带有查询参数的页面
                window.location.href = `?${queryParams.toString()}`;
            });
            $('#resetButton').click(function () {
                $('#searchItemName, #searchOperator, #searchHose,#searchitemCustomer').val('');
                $('#searchShipment_type').val('');
                performSearch();
            });

            // 初始化分页
            initPagination();
        });
    </script>
</body>
</html>